module(...,package.seeall)

require "sprite"

local seed = os.time();
math.randomseed( seed )

local ui = require("ui")
local life = require("life")

-- ===================== SKY BACKGROUND ====================== ---
function newSky(src)
    local localGroup = display.newGroup()

    local sky1 = display.newImage(src)
    local sky = display.newImage(src)

    sky1:setReferencePoint(display.BottomRightReferencePoint)
    sky:setReferencePoint(display.TopLeftReferencePoint)

    sky1.x = 0; sky.x = 0; sky1.y = 333; sky.y = 0

    local tPrevious = system.getTimer()

    function moveSky(e)
        local tDelta = e.time - tPrevious
        tPrevious = e.time
        
        local xOffset = ( 0.2 * tDelta )
        
        sky.x = sky.x + xOffset*0.25
        sky1.x = sky1.x + xOffset*0.25
            
        if sky.x >= 480 then
            sky.x = sky1.x - 1610
        end
        if sky1.x >= 1610 then
            sky1.x = sky.x
        end
    end
    
    localGroup:insert(sky1)
    localGroup:insert(sky)
    
    Runtime:addEventListener("enterFrame", moveSky)
    
    return localGroup
end
--- ===============================================================

----- =====================  PAUSE SCENE ========================------
function newPauseElements(transManager, pauseButton, sceneGroup, scene, upTimer)
	local localGroup = display.newGroup()
	
	local bg = display.newImage("images/pause/background_pause.png")
    bg:setReferencePoint(display.CenterReferencePoint)
    bg.x = _W/2; bg.y = _H/2;
	
    local reiniciar_btn = ui.newButton(
        { defaultSrc="images/pause/reiniciar.png",
          overSrc="images/pause/reiniciar_clicado.png",
          defaultX = 94,
          defaultY = 94,
          overX = 94,
          overY = 94,
          emboss = false
        } )
    reiniciar_btn.x = 320; reiniciar_btn.y = _H/2
        
    local retomar_btn = ui.newButton(
        { defaultSrc="images/pause/retomar.png",
          overSrc="images/pause/retomar_clicado.png",
          defaultX = 94,
          defaultY = 94,
          overX = 94,
          overY = 94,
          emboss = false
        } )
    retomar_btn.x = 160; retomar_btn.y = _H/2    

    local sound_btn = display.newGroup()
    
    local sound = display.newImage("images/pause/sound.png")
    sound.x = 0; sound.y = 0
    
    local nosound = display.newImage("images/pause/no_sound.png")
    nosound.x = 0; nosound.y = 0; nosound.alpha = 0
    
    sound_btn.x = 45; sound_btn.y = _H - 45
    
    sound_btn:insert(sound)
    sound_btn:insert(nosound)
    
    local exit_btn = display.newImage("images/pause/exit.png")
    exit_btn.x = _W - 35; exit_btn.y = _H - 35
    
	local function pause(event)
		if (event.phase == "ended") then
            _G.paused = true
			transManager:pauseAll()
			pauseButton.isVisible = false
            sceneGroup[9].isVisible = true
		end
	end
    
    local function resume(event)
        if (event.phase == "ended") then
            _G.paused = false
            transManager:resumeAll()
            pauseButton.isVisible = true
            sceneGroup[9].isVisible = false
        end
    end
    
    local function restart(event)
        if (event.phase == "ended") then
            _G.currentLevel = 1
            Runtime:removeEventListener("enterFrame", moveSky)
            media.stopSound()
            timer.cancel(upTimer)
            director:changeScene(scene, "overFromTop")
        end
    end
    
    local function nosound(event)
        local e = event.target
        local mute = (e[2].alpha == 1)
    
        if (event.phase == "ended") then
            if (mute) then
                media.playSound()
                e[1].alpha = 1
                e[2].alpha = 0
            else
            	media.pauseSound()
                e[1].alpha = 0
                e[2].alpha = 1
            end
        end
    end
    
    local function exit_event(event)
        if (event.phase == "ended") then
            Runtime:removeEventListener("enterFrame", moveSky)
			media.stopSound()
            _G.currentLevel = 1
            timer.cancel(upTimer)
            director:changeScene("menu", "overFromTop")
        end
    end
    
	pauseButton:addEventListener("touch", pause)
    retomar_btn:addEventListener("touch", resume)
    reiniciar_btn:addEventListener("touch", restart)
    sound_btn:addEventListener("touch", nosound)
    exit_btn:addEventListener("touch", exit_event)
	
	localGroup:insert(bg)
	localGroup:insert(reiniciar_btn)
	localGroup:insert(retomar_btn)
	localGroup:insert(sound_btn)
	localGroup:insert(exit_btn)
    
    localGroup.isVisible = false
    
	return localGroup
end
-----==============================================================

-- ========================= MONSTER ========================== ---
--Recebe o monstro (displayGroup) e o deslocamento vertical para entrar e sair do buraco
function monsterPlay(ms, dy, transManager, boss)
    local rMonster = math.random(1,3)
    
    if (boss) then
        rMonster = 4;
    end

    ms[1].vida = 1
    ms[2].vida = 2
    ms[3].vida = 1
    
	ms[1]:prepare("m_normal")
	ms[1]:play("m_normal")
    ms[2]:prepare("m_normal")
	ms[2]:play("m_normal")
    ms[3]:prepare("m_normal")
	ms[3]:play("m_normal")
	
    local speed = ms[rMonster].speed

    if (not _G.levelEnd) then
        transManager:add(ms[rMonster], {time=400, delay=math.random(0,3000), alpha=1, y=-dy, onComplete=function ()
			if (_G.currentMode == "arcade" and rMonster == 2 and math.random(1,2) == 1) then
				objetoPlay(ms.objeto, transManager)
			end
            transManager:add(ms[rMonster], {time=200, alpha=0, delay=math.random(200,1000)*speed, y=(2*dy), onComplete=function()
                monsterPlay(ms, dy, transManager, boss)
            end
            })
        end
        })
    end
	
end

local function tempoSplash(y)
	return (y > 550) and 750 or 1000
end

local function splashEvent(e)
	
	local obj = e.target
	-- Desativa o listener e prepara o sprite do "splash!"
	obj:removeEventListener("touch", splashEvent)
	obj:prepare("objSplash")
	obj:play("objSplash")
	-- Parar o sprite e esperar um tempo
	obj.transManager:cancelAll()
	obj.transManager:add(obj, {time=300, delay=0, alpha=0, y=obj.y, onComplete=function()
		-- Voltar ao seu devido lugar, lá no monstro.
		obj.transManager:add(obj, {time=0, delay=0, alpha=0, y=0, onComplete=function()
			obj:prepare("obj")
		end
		})
	end
	})
	
end
	
function objetoPlay(objeto, transManager)

	objeto[1]:prepare("obj")
	objeto[1]:play("obj")
	objeto.alpha = 1
	
	local offset = 800-objeto.y
	local tempo = tempoSplash(objeto.y)
	
	-- Reaparecer o objeto (alpha = 1)
	objeto[1].transManager:add(objeto[1], {time=0, alpha=1, onComplete=function() 
		-- Cria o listener pra matar o splash e joga o objeto até o jogador
		objeto[1]:addEventListener("touch", splashEvent)
		objeto[1].transManager:add(objeto[1], {time=tempo, delay=100, y=offset, onComplete=function()
			-- Splash! Atingiu. Passa 1 segundo esfregando o splash na sua cara, desativa o listener e tira uma vida sua
			objeto[1]:removeEventListener("touch", splashEvent)
			objeto[1]:prepare("objSplash")
			objeto[1]:play("objSplash")
			life.loseLife()
			objeto[1].transManager:add(objeto[1], {time=1000, delay=0, y=offset, onComplete=function()
				-- Voltar ao seu devido lugar, lá no monstro.
				objeto[1].transManager:add(objeto[1], {time=0, delay=0, alpha=0, y=0, onComplete=function()
					objeto[1]:prepare("obj")
				end
				})
			end
			})
		end
		})
	end
	})
	
end

function newHoleMonster(func, mX, mY, scale, params, sound)
    local monsters = display.newGroup()
    
    --- 1: GALINHA, 2: MONSTRO 2 TOUCH, 3: INOCENTE, 4: BOSS
    
    -- Recupera parametros
    local srcM1 = params.srcM1
    local srcM2 = params.srcM2
    local srcM3 = params.srcM3
    
    local swM1, shM1 = params.swM1, params.shM1
    local swM2, shM2 = params.swM2, params.shM2
    local swM3, shM3 = params.swM3, params.shM3
    
    -- Criação dos sprites
    local m1_sheet = sprite.newSpriteSheet(srcM1, swM1, shM1)
    local m2_sheet = sprite.newSpriteSheet(srcM2, swM2, shM2)
    local m3_sheet = sprite.newSpriteSheet(srcM3, swM3, shM3)
    
    local m1_set = sprite.newSpriteSet (m1_sheet, 1, 6)
    local m2_set = sprite.newSpriteSet (m2_sheet, 1, 6)
    local m3_set = sprite.newSpriteSet (m3_sheet, 1, 6)
    
    sprite.add (m1_set, "m_normal", 1, 4, 600, 0)
	sprite.add (m1_set, "m_pow", 5, 6, 1000, 1)
    
    sprite.add (m2_set, "m_normal", 1, 4, 600, 0)
	sprite.add (m2_set, "m_pow", 5, 6, 1000, 1)
    
    sprite.add (m3_set, "m_normal", 1, 4, 600, 0)
	sprite.add (m3_set, "m_pow", 5, 6, 1000, 1)
    
    local m1 = sprite.newSprite (m1_set)	
    local m2 = sprite.newSprite (m2_set)	
    local m3 = sprite.newSprite (m3_set)	
    
    m1.x = 0; m1.y = 0; m2.x = 0; m2.y = 0; m3.x = 0; m3.y = 0;
    
    monsters.x = mX
    monsters.y = mY
    monsters:scale(scale, scale)
    
    m1.alpha = 0; m2.alpha = 0; m3.alpha = 0
    
    -- Parametros para balaceamento
    m1.vida = 1; m2.vida = 2; m3.vida = 1
    m1.point = 1; m2.point = 3; m3.point = -5
    m1.speed = 1.5; m2.speed = 2; m3.speed = 2.5
	
	m1.sound = params.somM1
	m2.sound = params.somM2
	m3.sound = params.somM3
            
    monsters:insert(m1)
    monsters:insert(m2)
    monsters:insert(m3)
    
    m1:addEventListener("touch", func)
    m2:addEventListener("touch", func)
    m3:addEventListener("touch", func)
	
	monsters.objeto = newObjeto(mX, mY, params)
    
    return monsters
	
end

function newObjeto(mX, mY, params)

	local objeto = display.newGroup()
	
	objeto.x = mX
	objeto.y = mY
	objeto.alpha = 0
	
	local obj_set = sprite.newSpriteSet(sprite.newSpriteSheet(params.srcObj, params.swObj, params.shObj), 1, 4)
	
	sprite.add(obj_set, "obj", 1, 3, tempoSplash(objeto.y), 1)
	sprite.add(obj_set, "objSplash", 4, 1, 1, 1)
	local obj = sprite.newSprite(obj_set)
	obj.transManager = require("transitionManager").new()
	
	objeto:insert(obj)
	
	return objeto
	
end


--- ===================================================================

----================ TELAS COMBO, GAMEOVER, LEVELCOMPLETE =====================-----
function newTelaCheck(tipo, nextScene, upTimer)
    local localGroup = display.newGroup()
    local fade = display.newRect( 0, 0, _W * 3, _H * 3 )
    fade:setFillColor( 140, 140, 140 )
    fade.alpha = 0.5
    
    local img = ""
    
    local function touchEvent(e)
        if (e.phase == "ended") then
            Runtime:removeEventListener("enterFrame", moveSky)
            media.stopSound()
            timer.cancel(upTimer)
            director:changeScene(nextScene,"overFromTop")
        end
    end
    
    
    if (tipo == "combo") then
        img = display.newImage("images/backgrounds/combo.jpg")
        img.y = _H / 2 - 220
        img.alpha = 0.75
        fade.alpha = 0
        
        timer.performWithDelay(1000, function(e) img.alpha = 0; timer.cancel(e.source) end, 0)
    elseif (tipo == "gameover") then
        img = display.newImage("images/backgrounds/game_over.jpg")
        img:addEventListener("touch", touchEvent)
        img.y = _H / 2
    elseif (tipo == "end") then
        img = display.newImage("images/backgrounds/end.jpg")
        img:addEventListener("touch", touchEvent)
    else
        img = display.newImage("images/backgrounds/level_completed.jpg")
        img:addEventListener("touch", touchEvent)
        img.y = _H / 2
    end
    
    
    localGroup:insert(fade)
    localGroup:insert(img)
    
    return localGroup
end

